<template>
  <el-dialog v-model="dialogVisible" title="批量生成房间" width="500px">
    <el-form :model="formData" ref="formRef" :rules="rules" label-width="120px">
      <el-form-item label="所属楼栋">
        <el-input v-model="buildingName" disabled />
      </el-form-item>
      <el-form-item label="起始楼层" prop="startFloor">
        <el-input v-model.number="formData.startFloor" type="number" min="1" />
      </el-form-item>
      <el-form-item label="结束楼层" prop="endFloor">
        <el-input v-model.number="formData.endFloor" type="number" min="1" />
      </el-form-item>
      <el-form-item label="起始房间号" prop="startNumber">
        <el-input v-model.number="formData.startNumber" type="number" min="1" />
      </el-form-item>
      <el-form-item label="结束房间号" prop="endNumber">
        <el-input v-model.number="formData.endNumber" type="number" min="1" />
      </el-form-item>
      <el-form-item label="套内面积" prop="area">
        <el-input v-model.number="formData.area" type="number" min="0" />
        <template #append>㎡</template>
      </el-form-item>  
      <el-form-item label="物业面积" prop="propertyArea">
        <el-input v-model.number="formData.propertyArea" type="number" min="0" />
        <template #append>㎡</template>
      </el-form-item>
      <el-form-item label="初始状态" prop="status">
        <el-select v-model="formData.status">
          <el-option label="空闲" value="idle" />
          <el-option label="已占用" value="occupied" />
          <el-option label="维护中" value="maintenance" />
        </el-select>
      </el-form-item>
    </el-form>
    <template #footer>
      <el-button @click="dialogVisible = false">取消</el-button>
      <el-button type="primary" @click="handleGenerate">生成</el-button>
    </template>
  </el-dialog>
</template>

<script setup>
import { ref, inject } from 'vue';
import { ElMessage,ElLoading } from 'element-plus';
import request from '@/api/request'

// 状态管理
const dialogVisible = ref(false);
const formData = ref({
  startFloor: 1,
  endFloor: 1,
  startNumber: 1,
  endNumber: 10,
  area: 20,
  propertyArea: 20,
  status: 'idle'
});
const buildingInfo = ref(null);
const buildingName = ref('');
const formRef = ref(null);

// 验证规则
const rules = ref({
  startFloor: [
    { required: true, message: '请输入起始楼层', trigger: 'blur' },
    { type: 'number', min: 1, message: '起始楼层必须大于0', trigger: 'blur' }
  ],
  endFloor: [
    { required: true, message: '请输入结束楼层', trigger: 'blur' },
    { type: 'number', min: 1, message: '结束楼层必须大于0', trigger: 'blur' },
    {
      validator: (rule, value, callback) => {
        if (value < formData.value.startFloor) {
          callback(new Error('结束楼层不能小于起始楼层'));
        } else {
          callback();
        }
      },
      trigger: 'blur'
    }
  ],
  startNumber: [
    { required: true, message: '请输入起始房间号', trigger: 'blur' },
    { type: 'number', min: 1, message: '起始房间号必须大于0', trigger: 'blur' }
  ],
  endNumber: [
    { required: true, message: '请输入结束房间号', trigger: 'blur' },
    { type: 'number', min: 1, message: '结束房间号必须大于0', trigger: 'blur' },
    {
      validator: (rule, value, callback) => {
        if (value < formData.value.startNumber) {
          callback(new Error('结束房间号不能小于起始房间号'));
        } else {
          callback();
        }
      },
      trigger: 'blur'
    }
  ],
  area: [
    { required: true, message: '请输入房间套内面积', trigger: 'blur' },
    { type: 'number', min: 0, message: '套内面积必须大于等于0', trigger: 'blur' }
  ],
  propertyArea: [
    { required: true, message: '请输入物业面积', trigger: 'blur' },
    { type: 'number', min: 0, message: '物业面积必须大于等于0且小于8', trigger: 'blur' }
  ],
  status: [{ required: true, message: '请选择初始状态', trigger: 'change' }]
});

// 注入主组件的数据
const roomData = inject('roomData');
const emit = defineEmits(['success']);
let submitSuccessCallback = null;

// 打开弹窗
const open = (building, callback) => {
  buildingInfo.value = building;
  buildingName.value = building.name;
  submitSuccessCallback = callback

  formData.value = {
    startFloor: 1,
    endFloor: building.floors || 1,
    startNumber: 1,
    endNumber: 10,
    area: 20,
    propertyArea: 20,
    status: 'idle'
  };

  dialogVisible.value = true;
};
// 生成房间
const handleGenerate = () => {
  formRef.value.validate((valid) => {
    if (valid && buildingInfo.value) {

      const loading = ElLoading.service({
        lock: true,
        text: '正在批量生成...',
        background: 'rgba(0, 0, 0, 0.7)',
      })

      const { startFloor, endFloor, startNumber, endNumber, area,propertyArea, status } = formData.value;
      let newRooms = [];
      let maxId = Math.max(...roomData.map(item => item.id || 0), 0);

      // 生成房间数据
      for (let floor = startFloor; floor <= endFloor; floor++) {
        for (let num = startNumber; num <= endNumber; num++) {
          maxId++;
          newRooms.push({
            id: maxId,
            roomNumber: `${floor}${num.toString().padStart(2, '0')}`, // 格式化房间号，如101, 102...
            buildingId: buildingInfo.value.id,
            buildingName: buildingInfo.value.name,
            floor,
            area,
            propertyArea,
            status,
            description: `自动生成的房间`,
            isDeleted: false
          });
        }
      }
      // 新增
      request.post('/parkRoom/addBatch', newRooms).then(data => {
        dialogVisible.value = false;
        loading.close()
        if (data.success) {
          ElMessage.success(data.message);
          emit('success');
          // 提交成功后调用上层传入的回调
          if (submitSuccessCallback) {
            submitSuccessCallback("parkRoomList", buildingInfo.value.id);
          }
        } else {
          ElMessage.error(data.message);
          emit('fail');
        }
      }).catch(error => {
        loading.close()
        ElMessage.error('编辑异常', error)
      });
    }
  });
};

// 暴露方法
defineExpose({
  open
});
</script>
